 <?php
 use Illuminate\Support\Facades\DB;
/**
 * 时间格式
 * @param $time
 * @return false|string
 */

function uc_time_ago($ptime) {
    date_default_timezone_set('Asia/Shanghai');

    $ptime = strtotime($ptime);

    $etime = time() - $ptime;

    switch ($etime){
        case $etime <= 60:

            $msg = '刚刚';

            break;

        case $etime > 60 && $etime <= 60 * 60:

            $msg = floor($etime / 60) . ' 分钟前';

            break;

        case $etime > 60 * 60 && $etime <= 24 * 60 * 60:

            $msg = date('Ymd',$ptime)==date('Ymd',time()) ? '今天 '.date('H:i',$ptime) : '昨天 '.date('H:i',$ptime);

            break;

        case $etime > 24 * 60 * 60 && $etime <= 2 * 24 * 60 * 60:

            $msg = date('Ymd',$ptime)+1==date('Ymd',time()) ? '昨天 '.date('H:i',$ptime) : '前天 '.date('H:i',$ptime);

            break;

        case $etime > 2 * 24 * 60 * 60 && $etime <= 12 * 30 * 24 * 60 * 60:

            $msg = date('Y',$ptime)==date('Y',time()) ? date('m-d H:i',$ptime) : date('Y-m-d H:i',$ptime);

            break;

        default: $msg = date('Y-m-d H:i',$ptime);

    }

    return $msg;

}

function buildCategoryTree($items, $parentId = 0) {
    $branch = [];
 
    foreach ($items as $item) {
        if ($item['parent_id'] == $parentId) {
            $children = buildCategoryTree($items, $item['id']);
            if ($children) {
                $item['children'] = $children;
            }
            $branch[] = $item;
        }
    }
 
    return $branch;
}

//获取唯一序列号
function generateNum() {
    //strtoupper转换成全大写的
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $uuid = substr($charid, 0, 8).substr($charid, 8, 4).substr($charid,12, 4).substr($charid,16, 4).substr($charid,20,12);
    return $uuid;
}


/**
 * [生成随机字符串]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://blog.iinu.com.cn
 * @param  integer $length [生成的长度]
 * @param  integer $type   [生成的类型]
 * @return [type]   str       [description]
 * @php 随机码类型：0，数字+大写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
 */
function randCode($length = 5, $type = 0) {
    $arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 4 => "~@#$%^&*(){}[]|");
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } else if ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str[$i] = $string[rand(0, $count)];
        $code .= $str[$i];
    }
    return $code;
}

/**
 * [生成唯一字符串]
 * @E-mial wuliqiang_aa@163.com
 * @TIME   2017-04-07
 * @WEB    http://blog.iinu.com.cn
 * @ 0-存数字字符串；1-小写字母字符串；2-大写字母字符串；3-大小写数字字符串；4-字符；
 *   5-数字，小写，大写，字符混合
 * @param  integer $type   [字符串的类型]
 * @param  integer $length [字符串的长度]
 * @param  integer $time   [是否带时间1-带，0-不带]
 * @return [string]  $str    [返回唯一字符串]
 */
function randSole($type = 0,$length = 18,$time=0){
    $str = $time == 0 ? '':date('YmdHis',time());
    switch ($type) {
        case 0:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $str .= rand(0,9);
                }
            }
            break;
        case 1:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $rand = "qwertyuioplkjhgfdsazxcvbnm";
                    $str .= $rand[mt_rand(0,26)];
                }
            }
            break;
        case 2:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $rand = "QWERTYUIOPLKJHGFDSAZXCVBNM";
                    $str .= $rand[mt_rand(0,26)];
                }
            }
            break;
        case 3:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
                    $str .= $rand[mt_rand(0,35)];
                }
            }
            break;
        case 4:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $rand = "!@#$%^&*()_+=-~`";
                    $str .= $rand[mt_rand(0,17)];
                }
            }
            break;
        case 5:
            for((int)$i = 0;$i <= $length;$i++){
                if(mb_strlen($str) == $length){
                    $str = $str;
                }else{
                    $rand = "123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM!@#$%^&*()_+=-~`";
                    $str .= $rand[mt_rand(0,52)];
                }
            }
            break;
    }
    return $str;
}




//数据库友好的唯一字符串// 示例输出：Y7f3c9E1b5d2
function generateRandomString($length=12) {
    $bytes = openssl_random_pseudo_bytes($length);
    return substr(base64_encode($bytes), 0, $length);
}

// 获取客户端IP地址
function get_client_ip(){
   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
       $ip = getenv("HTTP_CLIENT_IP");
   else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
       $ip = getenv("HTTP_X_FORWARDED_FOR");
   else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
       $ip = getenv("REMOTE_ADDR"); // www.jbxue.com
   else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
       $ip = $_SERVER['REMOTE_ADDR'];
   else
       $ip = "unknown";
   return($ip);
}

function get_platform($BUY_PLATFORM) {
    if (in_array($BUY_PLATFORM, ["京东国际", "京东全球购"])) {
        $BUY_PLATFORM = "京东";
    } elseif (in_array($BUY_PLATFORM, ["天猫精选", "天猫超市", "天猫国际", "淘宝精选", "淘宝直播", "天猫国际官方直营"])) {
        $BUY_PLATFORM = "淘宝";
    } elseif (in_array($BUY_PLATFORM, ["抖音小店"])) {
        $BUY_PLATFORM = "抖音小店";
    } elseif (in_array($BUY_PLATFORM, ["唯品会"])) {
        $BUY_PLATFORM = "唯品会";
    } elseif (in_array($BUY_PLATFORM, ["拼多多"])) {
        $BUY_PLATFORM = "拼多多";
    } elseif (in_array($BUY_PLATFORM, ["中免集团", "中免日上"])) {
        $BUY_PLATFORM = "中免日上";
    }elseif (in_array($BUY_PLATFORM, ["美团外卖"])) {
        $BUY_PLATFORM = "美团";
    }else{
        $BUY_PLATFORM=$BUY_PLATFORM;
    }
    return $BUY_PLATFORM;
}


 /**
 * 获取ip地址的地理位置
 * @param type $ip  ip地址
 * @return type string
 */
 function getIPLocation($ip) {
    $url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=' . $ip;
    $ch = curl_init($url);
    //curl_setopt($ch,CURLOPT_ENCODING ,'utf8'); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 获取数据返回 
    $location = curl_exec($ch);
    $location = json_decode($location);
    curl_close($ch);
    $loc = "";
    if ($location === FALSE)
        return "";
    if (emptyempty($location->desc)) {
        $loc = $location->province . $location->city . $location->district . $location->isp;
    } else {
        $loc = $location->desc;
    }
    return $loc;

}
//逛逛组装数据
//当type为link时，link_text 这个是显示出来的文本内容，text 是链接地址


/**
 * PHP发送Json对象数据
 * @param $url 请求url
 * @param $data 发送的json字符串/数组
 * @return array
 */
function json_post($url, $postdata =[],$header=[])
{ 
    //设置头部信息
    if(empty($header)){
        $header = [
            'Content-Type:application/json; charset=utf-8',
        ];
    }
    
    //参数转化为json格式
    $postdata=json_encode($postdata);
    # 初始化一个curl会话
    $ch = curl_init();
    # 启用时会发送一个常规的POST请求
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    # 全部数据使用HTTP协议中的"POST"操作来发送。
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    # 将curl_exec()获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    # 一个用来设置HTTP请求头字段的数组
    curl_setopt($ch, CURLOPT_HTTPHEADER,$header);

    # curl_exec 执行一个cURL会话。
    $response = curl_exec($ch);
    # 关闭一个cURL会话
    curl_close($ch);
    $response=json_decode($response,true);
    return $response;


}

function removeProtocol($url) {
    return preg_replace('#^https?://#', '', $url);
}
function json_get($url, $params =[],$header=[])
{ 
    // 构造完整的URL
    $queryString = http_build_query($params);
    $fullUrl = $url . "?" . $queryString;
     
    // 初始化cURL会话
    $ch = curl_init($fullUrl);
    $headers = [

    ]; 
    // 设置请求头
    if(empty($headers)){
        $headers = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
        ];
    }
       
  
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     
    // 设置返回响应内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     
    // 执行请求
    $response = curl_exec($ch);
     
    // 检查请求是否成功
    if (curl_errno($ch)) {
        echo '请求失败: ' . curl_error($ch);
        exit();
    } else {
        $code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //if($code==200){
        $response=json_decode($response,true);
        return $response;
        //}
    }
     
    // 关闭cURL会话
    curl_close($ch);
}
function doGet($url,$params=[], $headers = []) {
    // 构造完整的URL
    $queryString = http_build_query($params);
    $fullUrl = $url . "?" . $queryString;
     
    // 初始化cURL会话
    $ch = curl_init($fullUrl);
     
    // 设置请求头
    if(empty($headers)){
        $headers = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'
        ];
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     
    // 设置返回响应内容
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     
    // 执行请求
    $response = curl_exec($ch);
     
    // 检查请求是否成功
    if (curl_errno($ch)) {
        echo '请求失败: ' . curl_error($ch);
        exit();
    } else {
        $code=curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($code==200){
            $response=json_decode($response,true);
            return $response;
        }
    }
     
    // 关闭cURL会话
    curl_close($ch);

}

function doGet2($url, $params = [], $headers = []) {
    // 构造完整的URL（只有在有参数时才添加?）
    if (!empty($params)) {
        $queryString = http_build_query($params);
        $fullUrl = $url . (strpos($url, '?') === false ? '?' : '&') . $queryString;
    } else {
        $fullUrl = $url;
    }
    
    // 初始化cURL会话
    $ch = curl_init($fullUrl);
    
    // 设置默认请求头
    if (empty($headers)) {
        $headers = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            'Accept: application/json, text/plain, */*'
        ];
    }
    
    // cURL配置选项
    $options = [
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ];
    
    curl_setopt_array($ch, $options);
    
    // 执行请求
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    
    // 关闭cURL会话
    curl_close($ch);
    
    // 错误处理
    if (!empty($error)) {
        throw new Exception('请求失败: ' . $error);
    }
    
    // 检查HTTP状态码
    if ($httpCode !== 200) {
        throw new Exception('HTTP请求失败，状态码: ' . $httpCode);
    }
    
    // 尝试JSON解码，如果失败返回原始内容
    $decodedResponse = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        // 如果不是JSON格式，返回原始响应
        return $response;
    }
    
    return $decodedResponse;
}
function checkHttp($str) {
    if (stripos($str, "http") !== false) {
        //字符串包含http或https（不区分大小写）
        
        return True;

    }else{
        return False;    
    }
}

/**
 * 彻底清理文本 - 去除所有空格和空白字符，保留标点
 */
function cleanTextThoroughly($text)
{
    if (empty($text)) {
        return '';
    }
    
    // 中文括号转英文括号
    $text = str_replace(['（', '）'], ['(', ')'], $text);
    
    // 使用正则去除所有空白字符，但保留标点符号
    $text = preg_replace('/\s+/', '', $text);
    
    return $text;
}

function extract_title_img_name_url($item, $platform){

    if ($platform == '淘宝'){
        if(!isset($item['result_list'])){
            return [
                'brand_name'=> '',
                'category_name'=> '',
                'title'=> '',
                "productImage"=> '',
                "productId"=> '',
                'item_id'=> '',
                "productName"=> '',
                "productUrl"=> '',
                "original_category_name"=>'',
                "original_brand_name"=>'',
            ];
        }
        $item = $item['result_list'][0];
        //dd($item);
        #获取原始品牌
        $original_brand_name="";
        if(isset($item['item_basic_info'])){
            $item_basic_info4=$item['item_basic_info'];
            if(isset($item_basic_info4['brand_name'])){
                $original_brand_name=$item_basic_info4['brand_name'];

            }
            
        }
        //dd($original_brand_name);
  
        #获取原始类目
        $original_category_name="";
        if(isset($item['item_basic_info'])){
            $level_one_category_name="";
            $category_name2="";
            $level_one=$item['item_basic_info'];

            if(isset($level_one['level_one_category_name'])){
                $level_one_category_name=$level_one['level_one_category_name'];
                $level_one_category_name="{$level_one_category_name}/";
            }

            if(isset($level_one['category_name'])){
                $category_name2=$level_one['category_name'];
            }
            $original_category_name="{$level_one_category_name}{$category_name2}";
            //dd($original_name);

            

        }
        
        //$original_name=
        //dd($item);
        #获取产品url
        $click_url=$item['publish_info'];
        if(isset($click_url['click_url'])){
            $click_url=$click_url['click_url'];
        }else{
            $click_url='';
        }
        $coupon_share_url=$item['publish_info'];
        if(isset($coupon_share_url['coupon_share_url'])){
            $coupon_share_url=$coupon_share_url['coupon_share_url'];
        }else{
            $coupon_share_url='';
        }

        if (empty($coupon_share_url)){
            $product_url=$click_url;
        }else{
            #取优惠券的url
            $product_url=$coupon_share_url;
        }
        #查看url是否拼接 https:
        $checkHttp=checkHttp($product_url);
        if (!$checkHttp){
            $product_url = "https://".$product_url;
        }
        $item_basic_info=$item['item_basic_info'];
        $brand_name='';
        if(isset($item_basic_info['brand_name'])){
            $brand_name=$item_basic_info['brand_name'];
        }
        $category_name='';
        if(isset($item_basic_info['category_name'])){
            $category_name=$item_basic_info['category_name'];
        }
        $title='';
        if(isset($item_basic_info['title'])){
            $title=$item_basic_info['title'];
        }
        $pict_url='';
        if(isset($item_basic_info['pict_url'])){
            $pict_url=$item_basic_info['pict_url'];
        }
        $original_category_name=cleanTextThoroughly($original_category_name);
        $original_brand_name=cleanTextThoroughly($original_brand_name);

        return [
            'brand_name'=> $brand_name,
            'category_name'=> $category_name,
            'title'=> $title,
            "productImage"=>$pict_url,
            "productId"=> $item['item_id'],
            'item_id'=> $item['item_id'],
            "productName"=> $title,
            "productUrl"=> $product_url,
            "original_category_name"=>$original_category_name,
            "original_brand_name"=>$original_brand_name
        ];


    }else if($platform == '京东') {
        if(!isset($item['data'])){
             return [
                'brand_name'=> '',
                'category_name'=> '',
                'title'=> '',
                "productImage"=> '',
                "productId"=> '',
                'item_id'=> '',
                "productName"=> '',
                "productUrl"=> '',
                "original_category_name"=>'',
                "original_brand_name"=>''
            ];
        }
        $item = $item['data'][0];
        //原始品牌名称
        $original_brand_name="";
        if(isset($item['brandName'])){
            $original_brand_name=$item['brandName'];
        }
        //dd($original_brand_name);
        //原始类目
        $original_category_name="";
        $cid1Name_arr2=[];
        if(isset($item['categoryInfo'])){
            $categoryInfo2=$item['categoryInfo'];
            
            foreach($categoryInfo2 as $k3=>$v3){
                if($k3=='cid1Name'){
                    $new_v3=str_replace("/", ",", $v3);

                    $cid1Name_arr2[]=$v3;
                }
                if($k3=='cid2Name'){
                    $new_v3=str_replace("/", ",", $v3);

                    $cid1Name_arr2[]=$v3;
                }

                if($k3=='cid3Name'){
                    $new_v3=str_replace("/", ",", $v3);

                    $cid1Name_arr2[]=$v3;
                }
            }
            
        }
        if(!empty($cid1Name_arr2)){
            $original_category_name=implode("/",$cid1Name_arr2);
        }
        
        //dd($original_name);
        $brandName='';
        if(isset($item['brandName'])){
            $brandName=$item['brandName'];
        }
        $categoryInfo=$item['categoryInfo'];
        $category_name=[];
        
        $cid1Name='';
        if(isset($categoryInfo['cid1Name'])){
            $cid1Name=$categoryInfo['cid1Name'];
        }
        $category_name[]=$cid1Name;

        $cid2Name='';
        if(isset($categoryInfo['cid2Name'])){
            $cid2Name=$categoryInfo['cid2Name'];
        }
        $category_name[]=$cid2Name;

        $cid3Name='';
        if(isset($categoryInfo['cid3Name'])){
            $cid3Name=$categoryInfo['cid3Name'];
        }
        $category_name[]=$cid3Name;
        
        $category_name_str = implode("、", $category_name);

        $skuName='';
        if(isset($item['skuName'])){
            $skuName=$item['skuName'];
        }
        $original_category_name=cleanTextThoroughly($original_category_name);
        $original_brand_name=cleanTextThoroughly($original_brand_name);

        return [
            'brand_name'=> $brandName,
            'category_name'=>$category_name_str,
            'title'=> $skuName,
            "productImage"=> $item['imageInfo']['imageList'][0]["url"],
            "productId"=> $item['itemId'],
            'item_id'=> $item['itemId'],
            "productName"=> $skuName,
            "productUrl"=> $item['materialUrl'],
            "original_category_name"=>$original_category_name,
            "original_brand_name"=>$original_brand_name

        ];


    }else if ($platform == '拼多多'){

        if(!isset($item['goods_details'])){
             return [
                'brand_name'=> '',
                'category_name'=> '',
                'title'=> '',
                "productImage"=> '',
                "productId"=> '',
                'item_id'=> '',
                "productName"=> '',
                "productUrl"=> '',
                "original_category_name"=> '',
                "original_brand_name"=>'',
            ];
        }
        //dd($item);
        $item = $item['goods_details'][0];
        $cat_ids = $item['cat_ids'];
        //dd($cat_ids);


        #4级别类目名称-展示保留
        $opt_name="";
        if(isset($item['opt_name'])){
            $opt_name=$item['opt_name'];
            $opt_name='/'.$opt_name;
        }
        $item['category_name']="";
        $status_lis = [];
        $category_name_arr2=[];
        # 判断类目是否存在
        foreach ($cat_ids as $i){
            //dd($i);
            $url='http://cgi-bin.lottefuture.com/python/pdd-goods-cat-get.php';
            $params = [
                'cat_id'=>$i
            ];
            $res_json =doGet2($url,$params);
           // dd($res_json);
            if ($res_json["status"] == 200){
               // dd($res_json);
                $status_lis[]=$res_json["status"];
                $cat_data="";
                if(isset($res_json['data'])){
                    $cat_data=$res_json['data'];
                    if(isset($cat_data['category_name'])){
                        $category_name_arr2[]=$cat_data['category_name'];
                    }
                }
                 
            }
     
        }

        if(!empty($category_name_arr2)){
            $rr=implode("/",$category_name_arr2);
            $item['category_name']=$rr;
        }
        //dd($item['category_name']);
        if (!in_array('200',$status_lis)){
            //拼多多 类目ID查询失败,类目id => {_}
            return false;
        }
        //商品原始品牌
        $original_brand_name="";
        if(isset($item['brand_name'])){
            $original_brand_name=$item['brand_name'];
        }
        //dd($item);
        //商品原始类目
        $original_category_name="";
        if(isset($item['category_name'])){
            $original_category_name=$item['category_name'];
        }
        
        ///dd($original_name);
        $brand_name='';
        if(isset($item['brand_name'])){
            $brand_name=$item['brand_name'];
        }

        $category_name='';
        if(isset($item['category_name'])){
            $category_name=$item['category_name'];
        }

        $goods_name='';
        if(isset($item['goods_name'])){
            $goods_name=$item['goods_name'];
        }

        $goods_image_url='';
        if(isset($item['goods_image_url'])){
            $goods_image_url=$item['goods_image_url'];
        }

        $goods_sign='';
        if(isset($item['goods_sign'])){
            $goods_sign=$item['goods_sign'];
        }


        $original_category_name=cleanTextThoroughly($original_category_name);
        $original_brand_name=cleanTextThoroughly($original_brand_name);
        return [
            'brand_name'=> $brand_name,
            'category_name'=> $category_name,
            'title'=> $goods_name,
            "productImage"=> $goods_image_url,
            "productId"=> $goods_sign,
            'item_id'=> $goods_sign,
            "productName"=> $goods_name,
            "productUrl"=> '',
            "original_category_name"=>$original_category_name,
            "original_brand_name"=>$original_brand_name,
        ];

       

    }else if ($platform == '唯品会'){
        if(!isset($item['result'])){
            return [
                'brand_name'=> '',
                'category_name'=> '',
                'title'=> '',
                "productImage"=> '',
                "productId"=> '',
                'item_id'=> '',
                "productName"=> '',
                "productUrl"=> '',
                "original_category_name"=>'',
                "original_brand_name"=>''
            ];   
        }
        $item = $item['result'][0];
        $brandName='';
        //商品原来品牌
        $original_brand_name="";
        if(isset($item['brandName'])){
            $original_brand_name=$item['brandName'];
        }
       
        //dd($item);
        if(isset($item['brandName'])){
            $brand_name=$item['brandName'];
        }

        $category_name=[];
        
        $cat1stName='';
        if(isset($item['cat1stName'])){
            $cat1stName=$item['cat1stName'];
        }
        $category_name[]=$cat1stName;

        $cat2ndName='';
        if(isset($item['cat2ndName'])){
            $cat2ndName=$item['cat2ndName'];
        }
        $category_name[]=$cat2ndName;

        $categoryName='';
        if(isset($item['categoryName'])){
            $categoryName=$item['categoryName'];
        }
        $category_name[]=$categoryName;

        $category_name_str = implode("/", $category_name);

        $goodsName='';
        if(isset($item['goodsName'])){
            $goodsName=$item['goodsName'];
        }

        $goodsMainPicture='';
        if(isset($item['goodsMainPicture'])){
            $goodsMainPicture=$item['goodsMainPicture'];
        }

        $destUrl='';
        if(isset($item['destUrl'])){
            $destUrl=$item['destUrl'];
        }

        $original_category_name=cleanTextThoroughly($category_name_str);
        $original_brand_name=cleanTextThoroughly($original_brand_name);

        return [
            'brand_name'=> $brand_name,
            'category_name'=> $category_name_str,
            'title'=> $goodsName,
            "productImage"=> $goodsMainPicture,
            "productId"=> $item['goodsId'],
            'item_id'=> $item['goodsId'],
            "productName"=> $goodsName,
            "productUrl"=> $destUrl,
            "original_category_name"=>$original_category_name,
            "original_brand_name"=>$original_brand_name
        ];

    }else if ($platform == '抖音小店'){
        $item = $item['data'];
        $brandName='';
        if(isset($item['standard_brand'])){
            $brand_name=$item['standard_brand'];
        }

        $category_name=[];
        
        $brand='';
        if(isset($item['brand'])){
            $brand=$item['brand'];
        }
        $category_name[]=$brand;

        $standard_brand='';
        if(isset($item['standard_brand'])){
            $standard_brand=$item['standard_brand'];
        }
        $category_name[]=$standard_brand;

        $original_brand='';
        if(isset($item['original_brand'])){
            $original_brand=$item['original_brand'];
        }
        $category_name[]=$original_brand;

        $category_name_str = implode("、", $category_name);


        $name='';
        if(isset($item['name'])){
            $name=$item['name'];
        }

        $screen_img='';
        if(isset($item['screen_img'])){
            $screen_img=$item['screen_img'];
        }


        return [
            'brand_name'=> $brand_name,
            'category_name'=>$category_name_str,
            'title'=> $name,
            "productImage"=>$screen_img,
            "productId"=> $item['product_id'],
            'item_id'=> $item['product_id'],
            "productName"=> $name,
            "productUrl"=> '',
        ];

        
    # 其它平台解析
    }else{
        return [];
    }

}


/*京东
https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.goods.query
拼多多
https://open.pinduoduo.com/application/document/api?id=pdd.ddk.oauth.goods.detail
淘宝
https://open.taobao.com/api.htm?docId=64758&docType=2&scopeId=13991
唯品会
https://vop.vip.com/home#/api/method/detail/com.vip.adp.api.open.service.UnionGoodsV2Service-2.0.0/getByGoodsIdsV2WithOauth*/

function calculateMoneyCount($platformData, $platformName) {
    try {
        if ($platformName == '淘宝') {
            if(!isset($platformData['result_list'])){
                $result=[
                    'commission_rate'=>0.00,
                    'subsidy_rate'=>0.00,
                    'commission_amount'=>0.00,
                    'total_commission_rate'=>0.00,
                    'income_rate'=>0.00,
                    'is_owner'=>false,
                ];
                return $result;
            }
            /*
                "publish_info": {
                "income_info": {
                    "commission_amount": "8.4",
                    "commission_rate": "1500",
                    "subsidy_amount": "2.52",
                    "subsidy_rate": "450",
                    "subsidy_type": "超级淘客佣金膨胀",
                    "subsidy_upper_limit": "18"
                },
                "income_rate": "19.5",
                "two_hour_promotion_sales": 100
            }
            佣金比例： income_rate  19.5   commission_rate / 100 +  subsidy_rate /100 
            佣金金额： commission_amount + subsidy_amount 8.4 + 2.52
            */
            $item = $platformData['result_list'][0]['publish_info'];

            $commission_rate = floatval($item['income_info']['commission_rate']);
            if(!empty($commission_rate)){
                $commission_rate=$commission_rate / 100;
            }else{
                $commission_rate=0.00;
            }
            $commission_amount = floatval($item['income_info']['commission_amount']);
            if(!empty($commission_amount)){
                $commission_amount=$commission_amount;
            }else{
                $commission_amount=0.00;
            }
            $subsidy_rate = floatval($item['income_info']['subsidy_rate']);
            if(!empty($subsidy_rate)){
                $subsidy_rate=$subsidy_rate / 100;
            }else{
                $subsidy_rate=0.00;
            }
            $subsidy_amount = floatval($item['income_info']['subsidy_amount']);

            $income_rate = floatval($item['income_rate']);

            #return income_rate + commission_rate / 100 + subsidy_rate / 100, commission_amount + subsidy_amount, None
            $total_commission_rate =$income_rate +$commission_rate + $subsidy_rate;
            $total_commission_amount =$commission_amount + $subsidy_amount;
            $result=[
                'commission_rate'=>$commission_rate,
                'subsidy_rate'=>$subsidy_rate,
                'commission_amount'=>$commission_amount,
                'total_commission_rate'=>$total_commission_rate,
                'income_rate'=>$income_rate,
                'is_owner'=>false,
            ];

            return $result;

        } elseif ($platformName == '京东') {
            /*
                "commissionInfo": {
                "commission": 0.36,
                "commissionShare": 1.3,
                "couponCommission": 0.34,
                "endTime": 1751299199000,
                "isLock": 1,
                "plusCommissionShare": 1.3,
                "startTime": 1749052800000
            }
            "owner": "g", //g=自营，p=pop
            
            佣金比例：commissionShare 1.3
            佣金金额：commission 0.36
            
            非自营商品 owner = p 减去百分之10的技术服务费
            
            佣金金额：commission * 0.9  0.32
            
            $.data[0].commissionInfo
            */
            if(!isset($platformData['data'])){
                $result=[
                    'commission_rate'=>0.00,
                    'subsidy_rate'=>0.00,
                    'commission_amount'=>0.00,
                    'total_commission_rate'=>0.00,
                    'income_rate'=>0.00,
                    'is_owner'=>false,
                ];
                return $result;
            }

            $item = $platformData['data'][0];

            $commission_rate = floatval($item['commissionInfo']['commissionShare']);

            if(empty($commission_rate)){
                $commission_rate=0.00;
            }

            $commission_amount = floatval($item['commissionInfo']['commission']);

            $owner = $item['owner'];
            $is_owner=false;
            if ($owner == 'g') {
                $commission_amount=$commission_amount * 0.9;
                $is_owner=true;
            }


            $subsidy_rate=0.00;
            $subsidy_amount=0.00;
            $income_rate=0.00;
            $total_commission_rate =$income_rate +$commission_rate + $subsidy_rate;
            $total_commission_amount =$commission_amount + $subsidy_amount;

            

            $result=[
                'commission_rate'=>$commission_rate,
                'subsidy_rate'=>$subsidy_rate,
                'commission_amount'=>$commission_amount,
                'total_commission_rate'=>$total_commission_rate,
                'income_rate'=>$income_rate,
                'is_owner'=>false,
            ];
            return $result;

        } elseif ($platformName == '拼多多') {
            /*
            "min_group_price": 4990, 商品价格
            "promotion_rate": 135,  佣金比例
            
            佣金比例：promotion_rate / 100
            佣金金额：min_group_price / 100 * promotion_rate / 100
            
            $.goods_details[0].promotion_rate
            $.goods_details[0].min_group_price
            */

            if(!isset($platformData['goods_details'])){
                $result=[
                    'commission_rate'=>0.00,
                    'subsidy_rate'=>0.00,
                    'commission_amount'=>0.00,
                    'total_commission_rate'=>0.00,
                    'income_rate'=>0.00,
                    'is_owner'=>false,
                ];
                return $result;
            }

            $item = $platformData['goods_details'][0];
            //dd($item);

            $commission_rate = floatval($item['promotion_rate']);
            if(!empty($commission_rate)){
                $commission_rate = $commission_rate / 100;
            }else{
                $commission_rate =0.00;
            }

            $min_group_price = floatval($item['min_group_price']);
            if(!empty($min_group_price)){
                $min_group_price = $min_group_price / 100;
            }else{
                $min_group_price =0.00;
            }

            
            $commission_amount = $min_group_price * $commission_rate;

            $subsidy_amount=0.00;
            $subsidy_rate=0.00;
            $income_rate=0.00;
            $total_commission_rate =$income_rate +$commission_rate + $subsidy_rate;
           // dd($subsidy_amount);
            $total_commission_amount =$commission_amount + $subsidy_amount;
            //die("sdfs");
            $result=[
                'commission_rate'=>$commission_rate,
                'subsidy_rate'=>$subsidy_rate,
                'commission_amount'=>$commission_amount,
                'total_commission_rate'=>$total_commission_rate,
                'income_rate'=>$income_rate,
                'is_owner'=>false,
            ];

            //dd($result);
            return $result;

        } elseif ($platformName == '唯品会') {
            /*
            "commissionRate": "0.5",
            "commission": "4.21",
            
            佣金比例：commissionRate
            佣金金额：commission
            
            $.result[0].commissionRate
            $.result[0].commission
            */
            if(!isset($platformData['result'])){
                $result=[
                    'commission_rate'=>0.00,
                    'subsidy_rate'=>0.00,
                    'commission_amount'=>0.00,
                    'total_commission_rate'=>0.00,
                    'income_rate'=>0.00,
                    'is_owner'=>false,
                ];
                return $result;
            }
            $item = $platformData['result'][0];

            $commission_rate = floatval($item['commissionRate']);
            $commission_amount = floatval($item['commission']);




            $subsidy_rate=0.00;
            $income_rate=0.00;
            $subsidy_amount=0.00;
            $total_commission_rate =$income_rate +$commission_rate + $subsidy_rate;
            $total_commission_amount =$commission_amount + $subsidy_amount;
            $result=[
                'commission_rate'=>$commission_rate,
                'subsidy_rate'=>$subsidy_rate,
                'commission_amount'=>$commission_amount,
                'total_commission_rate'=>$total_commission_rate,
                'income_rate'=>$income_rate,
                'is_owner'=>false,
            ];

            return $result;
        } else {
            // 其它平台解析
            return null;
        }
    } catch (Exception $e) {
        // 失败
        return null;
    }
}


//四舍六入五单双 
function _round($num,$n=2){
    $pow = pow(10,$n);
    $con_a = floor(round($num * $pow * 10,1));
    $con_b = floor(round($num * $pow,1));
    $con_c = ($num * $pow * 10);
    $len = strlen(str_replace('.','',$con_c))-strlen($con_a);
 
    //舍去位为5 && 舍去位后无有效数字 && 舍去位前一位是偶数 ->不进位
    if(($con_a % 5 == 0) && bccomp($con_a,$con_c,($len))==0 && ($con_b % 2 ==0) ){
        return floor($num * $pow)/$pow;
    }else{//四舍五入
        return round($num,$n);
    }


}


//获取某个分类的所有父分类
function getParentCategories($categories,$categoryId) {
    $parentIds = [];
    foreach ($categories as $category) {
        if ($category['id'] == $categoryId) {
            $parentIds[] = $category;
            if ($category['parent_id'] != 0) { // 如果不是顶级分类，继续查找父分类
                $parentIds = array_merge($parentIds, getParentCategories($category['parent_id'], $categories));
            }
            break; // 找到当前分类后退出循环
        }
    }
    return $parentIds;
}

//递归获取所有的子分类的ID
function get_all_child($array,$id){
    $arr = [];
    foreach($array as $v){
        if($v['pid'] == $id){
            $arr[] = $v['id'];
            $arr = array_merge($arr,get_all_child($array,$v['id']));
        };
    };
    return $arr;
}

function fetch_platform_data($platform,$productId,$url){
    if(empty($url)){
        return 0;
    }
    if ($platform!='抖音小店'){
        # 定义参数
        $params=[
            'itemId'=> $productId
        ];
        # 定义头部
        $headers=[
            'Connection'=>'Close'
        ];
        
        # 发送GET请求
        $response = doGet($url,$params,$headers);

    }else{
        # 定义参数
        $params = [
            'product_id'=> $productId,
            'platform'=> $platform,
            'user_id'=>'0'
        ];
       # 定义头部
        $headers=[
            'Connection'=>'Close'
        ];
        
        
        # 发送GET请求
        $response = doGet($url,$params,$headers);
    }
    $extract=extract_title_img_name_url($response, $platform);
    return $extract;
}
/**
 * 根据指定时间获取近7天的日期范围
 * 
 * @param string $datetime 输入时间字符串，格式：Y-m-d H:i:s
 * @param bool $include_time 是否在结果中包含时间部分
 * @return array 包含开始日期和结束日期的数组
 */
function getLast7DaysRange($datetime, $include_time = true) {
    // 将输入字符串转换为时间戳
    $timestamp = strtotime($datetime);
    
    // 计算7天前的时间戳
    $start_timestamp = strtotime('-7 days', $timestamp);
    
    // 根据是否需要时间部分格式化输出
    $format = $include_time ? 'Y-m-d H:i:s' : 'Y-m-d';

    
    return [
        'start_date' => date($format, $start_timestamp),
        'end_date' => date($format, $timestamp)
    ];
}

// 判断时间是否在有效期内
function isExpired($startTime, $endTime) {
     // 转换为时间戳
    $startTimestamp = strtotime($cleanStartTime);
    $endTimestamp = strtotime($cleanEndTime);
    $currentTimestamp = time();
    if ($currentTimestamp < $startTimestamp) {
        return "尚未开始";
    } elseif ($currentTimestamp > $endTimestamp) {
        return "已过期";
    } else {
        return "有效期内";
    }

}
//推荐方案-模板
/**
 * 生成商品描述文本
 * @param float $amount 实际付款金额
 * @param float $commissionRate 佣金比例（如0.05表示5%）
 * @param float $subsidyRate 补贴比例（如0.02表示2%）
 * @param string $platform 平台标识（taobao/jd/pdd）
 * @param string $grade 用户等级（星粉/星光/星辰）
 * @return float 最终展示的佣金金额（保留两位小数）
 * 
 */
function generateProductDescription(array $data): string {
    // 提取数据或设置默认值
    $shopName = $data['shop_name'] ?? $data['platform_name'] ?? '该店铺';
    $unit_price = $data['unit_price'] ?? '未知1';
    $couponPrice = $data['coupon_price'] ?? '未知2';
    $fullReduction = $data['full_reduction'] ?? '满减优惠';
    $quantity = $data['quantity'] ?? '几';
    $actualPayment = $data['actual_payment'] ?? '未知3';
    $commission = $data['commission'] ?? '未知4';
    $unitPrice = $data['unit_price'] ?? '未知5';
    $couponInfo = $data['coupon_info'] ?? '';
    $discountActivity = $data['discount_activity'] ?? '';
    $reductionActivity = $data['reduction_activity'] ?? '';
    
    // 根据数据选择模板
    if (isset($data['commission']) && isset($data['unit_price'])) {
        // 使用返利模板
        return "【{$shopName}】此款目前活动售价【{$couponPrice}】，参与【{$fullReduction}】，下单【{$quantity}】件，凑单后实付【{$actualPayment}】元，在星返购买还可得佣金约【{$commission}】元，单价到手【{$unitPrice}】元";
    } else {
        // 使用普通优惠模板
        $activityText = "";
        if ($discountActivity) {
            $activityText .= "参与【{$discountActivity}】";
        }
        if ($reductionActivity) {
            if ($activityText) $activityText .= "，";
            $activityText .= "【{$reductionActivity}】";
        }
        if ($activityText) {
            $activityText .= "优惠活动";
        }
        
        return "【{$shopName}】此款目前活动售价【{$unit_price}】元" .
               ($couponInfo ? "，使用【{$couponInfo}】券" : "") .
               ($activityText ? "，{$activityText}" : "") .
               "，下单【{$quantity}】件，实付低至【{$couponPrice}】，近期好价";
    }
}

//重新整理下划线
function platform_name_product_id($platform_name,$product_id)
{
/*    淘宝- 
    京东_
    拼多多_*/
    $ar=[];
    switch ($platform_name) {
        case "淘宝":
            $product_id=str_replace("-", "_", $product_id);
            break;
        case "京东":
            break;
        case "拼多多":
            break;
        case "云选":
            break;
        case "微信小店":
            $product_id=str_replace("-", "_", $product_id);
            break;
        default:
            $product_id=$product_id;
    }
    $result=[];
    $ar=explode('_',$product_id);
    if(count($ar)>2){
        $str=[];
        foreach($ar as $k3=>$v3){
            if($k3!=0){
                $str[]=$v3;
            }
        }
        $result['0']=$ar['0'];
        $result['1']=implode('_',$str);
        //dd($str);
    }else{
        $result=$ar;
    }
    if(is_array($ar)&& count($ar)==1){
        //die("sdfs");
        $ar[1]=$product_id;
        $result=$ar;
    }
   // dd($result);
    return $result;

}

# 获取平台比例
function platform_rate($platform=""){

    if(!empty($platform)){
        $sql="SELECT `platform_name`,`platform_rate` FROM `module_platforms` where platform_name='{$platform}' ";
    }else{
        $sql=" SELECT `platform_name`,`platform_rate` FROM `module_platforms` ";
       
    }
   // die($sql);
    $list=DB::select($sql);
    $list = array_map('get_object_vars', $list);
    $platformNames=[];
    foreach($list as $k=>$v){
        $key=$v['platform_name'];
        $platformNames[$key]=$v['platform_rate'];
    }
    if(!empty($platform)){
        return $platformNames[$platform] ?? null;
    }else{
        return $platformNames ?? null;
    }


}
#获取平台比例-心动日记
function platform_xdrj_rate($platform=""){

    if(!empty($platform)){
        $sql="SELECT `platform_name`,`platform_rate` FROM `module_platforms_xdrj` where platform_name='{$platform}' ";
    }else{
        $sql=" SELECT `platform_name`,`platform_rate` FROM `module_platforms_xdrj` ";
       
    }
   // die($sql);
    $list=DB::select($sql);
    $list = array_map('get_object_vars', $list);
    $platformNames=[];
    foreach($list as $k=>$v){
        $key=$v['platform_name'];
        $platformNames[$key]=$v['platform_rate'];
    }
    if(!empty($platform)){
        return $platformNames[$platform] ?? null;
    }else{
        return $platformNames ?? null;
    }


}
# 计算用户等级比例
function user_level_rate($levelId){

    $gradeRatio = match ($levelId) {
        '1' => 0.94,
        '2' => 0.96,
        '3' => 1.00,
        default =>0.00
    };
    return $gradeRatio;
}

#星粉94%，星光96%，星辰100%
#获取京东会员等级
#补贴比例 $subsidy_rate
#佣金比例 $commission_rate
#用户等级比例  $level
#平台名称   $platform_name 
#金额      $unit_price

function get_jd_money($subsidy_rate,$commission_rate,$levelId,$platform_name,$unit_price)
{
    $level_rate=user_level_rate($levelId);
    $platform_rate=platform_rate($platform_name);
    $estimate_commission_rate=($subsidy_rate+$commission_rate)*$level_rate*$platform_rate;
    #京东会员佣金
    $estimate_commission=$unit_price*$estimate_commission_rate;
    $result=[
        'estimate_commission'=>$estimate_commission,
        'estimate_commission_rate'=>$estimate_commission_rate
    ];
    return $result;
}
if (!function_exists('getClientIp')) {
    /**
     * 获取客户端真实IP地址
     * 
     * @return string
     */
    function getClientIp()
    {
        $ip = '';
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        
        // 处理多个IP的情况（如经过代理）
        if (strpos($ip, ',') !== false) {
            $ips = explode(',', $ip);
            $ip = trim($ips[0]);
        }
        
        return $ip;
    }
}
if (!function_exists('getLocationByIp')) {
    /**
     * 根据IP地址获取地理位置信息
     * 
     * @param string $ip IP地址
     * @return array
     */
    function getLocationByIp($ip = '')
    {
        if (empty($ip)) {
            $ip = getClientIp();
        }
       // dd($ip);
        // 本地IP或无效IP
        if ($ip === '127.0.0.1' || $ip === '::1' || !filter_var($ip, FILTER_VALIDATE_IP)) {
            return [
                'country' => '本地',
                'region' => '本地',
                'city' => '本地',
                'isp' => '',
                'lat'=>'',
                'lon'=>'',
                'ip'=>$ip,
            ];
        }
        
        // 使用IPAPI服务获取地理位置信息
        $url = "http://ip-api.com/json/{$ip}?lang=zh-CN";


        
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($ch);
            curl_close($ch);
            
            $data = json_decode($response, true);
            
            if ($data && $data['status'] === 'success') {
                $data['city'] = str_replace('市', '',$data['city']);
                return [
                    'country' => $data['country'] ?? '',
                    'region' => $data['regionName'] ?? '',
                    'city' => $data['city'] ?? '',
                    'isp' => $data['isp'] ?? '',
                    'lat' => $data['lat'] ?? '',
                    'lon' => $data['lon'] ?? '',
                    'ip'=>$ip,
                ];
            }
        } catch (Exception $e) {
            // 记录错误或静默处理
        }

        
        return [
            'country' => '',
            'region' => '',
            'city' => '',
            'isp' => '',
            'lat'=>'',
            'lon'=>'',
            'ip'=>$ip
           ];
    }
}


function get_ip_location($ip="") {
    if (empty($ip)) {
        $ip = getClientIp();
    }
    $apis = [
        [
            'url' => "https://ipapi.co/{$ip}/json/",
            'field' => 'city' // 城市字段名
        ],
        [
            'url' => "http://ip-api.com/json/{$ip}?lang=zh-CN",
            'field' => 'city'
        ],
        [
            'url' => "https://api.ip.sb/geoip/{$ip}",
            'field' => 'city'
        ],
        [
            'url' => "https://ipinfo.io/{$ip}/json",
            'field' => 'city'
        ]
    ];
    
    foreach ($apis as $api) {
        try {
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $api['url'],
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_CONNECTTIMEOUT => 3,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            
            if ($httpCode === 200 && !empty($response)) {
                $data = json_decode($response, true);
                if (isset($data[$api['field']]) && !empty($data[$api['field']])) {
                    $data[$api['field']] = str_replace('市', '',$data[$api['field']]);
                    return [
                        'city' => $data[$api['field']] ?? '',
                        'region' => $data['region'] ?? $data['state'] ?? '',
                        'country' => $data['country'] ?? '',
                        'isp' => $data['isp'] ?? $data['org'] ?? '',
                        'source' => $api['url']
                    ];
                }
            }
        } catch (Exception $e) {
            // 继续尝试下一个API
            continue;
        }
    }
    
    return null;
}


/**
 * 根据自定义字段去重
 * 
 * @param array $array 需要去重的二维数组
 * @param array $fields 用于去重的字段名数组
 * @param bool $normalizeNumbers 是否对数值字段进行标准化处理
 * @return array 去重后的数组
 */
function arrayUniqueByFields($array, $fields, $normalizeNumbers = true) {
    $result = [];
    $seen = []; // 用于记录已经出现过的组合
    
    // 遍历数组
    foreach ($array as $item) {
        // 生成当前项目的唯一标识键
        $keyParts = [];
        foreach ($fields as $field) {
            if (isset($item[$field])) {
                $value = $item[$field];
                
                // 如果启用数值标准化，对数值字段进行处理
                if ($normalizeNumbers && is_numeric($value)) {
                    $value = strval(floatval($value));
                }
                
                $keyParts[] = $field . ':' . $value;
            }
        }
        $key = implode('|', $keyParts);
        
        // 如果这个组合还没出现过，则添加到结果中
        if (!isset($seen[$key])) {
            $seen[$key] = true;
            $result[] = $item;
        }
    }
    
    return $result;
}
/**
 * 计算字符串相似度（Levenshtein距离）
 */
function stringSimilarity($str1, $str2) {
    $len1 = strlen($str1);
    $len2 = strlen($str2);
    $maxLen = max($len1, $len2);
    
    if ($maxLen === 0) return 100;
    
    $distance = levenshtein($str1, $str2);
    $similarity = (1 - $distance / $maxLen) * 100;
    
    return max(0, min(100, $similarity));
}
/**
 * 模糊搜索关键字
 */
function fuzzySearch($string, $keyword, $threshold = 70) {
    $words = preg_split('/\s+/', $string);
    
    foreach ($words as $word) {
        $similarity = stringSimilarity($word, $keyword);
        if ($similarity >= $threshold) {
            return true;
        }
    }
    
    return false;
}
/**
 * 检查字符串是否包含关键字（不区分大小写）
 */
function containsKeyword($string, $keyword) {
    return stripos($string, $keyword) !== false;
}
/**
 * 判断并补全日期格式
 * @param string $dateString 日期字符串
 * @return string 补全后的日期时间格式
 */
function completeDateTime($dateString) {
    // 判断是否为 "YYYY-MM-DD" 格式
    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateString)) {
        return $dateString . ' 00:00:00';
    }
    
    // 判断是否为 "YYYY-MM-DD HH:MM:SS" 格式
    if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $dateString)) {
        return $dateString; // 已经是完整格式，直接返回
    }
    
    // 如果不是以上格式，返回原字符串或抛出异常
    return $dateString;
}

/**
 * 检查时间是否过期
 * @param mixed $startTime 开始时间（时间戳或日期字符串）
 * @param mixed $endTime 结束时间（时间戳或日期字符串）
 * @return int 1-过期, 2-有效
 */
function checkExpired($startTime, $endTime)
{
    $currentTime = time();
    
    // 转换为时间戳
    $startTimestamp = is_numeric($startTime) ? $startTime : strtotime($startTime);
    $endTimestamp = is_numeric($endTime) ? $endTime : strtotime($endTime);
    
    // 验证时间有效性
    if ($startTimestamp === false || $endTimestamp === false) {
        return 1; // 时间格式无效，视为过期
    }
    
    if ($startTimestamp > $endTimestamp) {
        return 1; // 开始时间大于结束时间，视为过期
    }
    
    if ($currentTime < $startTimestamp || $currentTime > $endTimestamp) {
        return 1; // 不在有效期内
    }

/*    if ($currentTime < $startTimestamp) {
        // 还未开始
        return 3; // 还未开始
    }

    if ($currentTime > $endTimestamp) {
        # 活动已结束
        return 1;
    }*/
    
    return 2; // 在有效期内
}

// 使用示例
#$is_expired = checkExpired($start_times, $end_times);
/**
 * 检查时间状态（更详细）
 * @param mixed $startTime 开始时间
 * @param mixed $endTime 结束时间
 * @return array 包含状态和详细信息
 */
function checkTimeStatus($startTime, $endTime)
{
    $currentTime = time();
    
    $startTimestamp = is_numeric($startTime) ? $startTime : strtotime($startTime);
    $endTimestamp = is_numeric($endTime) ? $endTime : strtotime($endTime);
    
    if ($startTimestamp === false || $endTimestamp === false) {
        return [
            'is_expired' => 1,
            'status' => 'invalid_time',
            'message' => '时间格式无效'
        ];
    }
    
    if ($startTimestamp > $endTimestamp) {
        return [
            'is_expired' => 1,
            'status' => 'invalid_range',
            'message' => '开始时间不能大于结束时间'
        ];
    }
    
    if ($currentTime < $startTimestamp) {
        return [
            'is_expired' => 1,
            'status' => 'not_started',
            'message' => '活动尚未开始',
            'remaining' => $startTimestamp - $currentTime
        ];
    }
    
    if ($currentTime > $endTimestamp) {
        return [
            'is_expired' => 1,
            'status' => 'expired',
            'message' => '活动已结束',
            'passed' => $currentTime - $endTimestamp
        ];
    }
    
    return [
        'is_expired' => 2,
        'status' => 'active',
        'message' => '活动进行中',
        'remaining' => $endTimestamp - $currentTime
    ];
}

// 使用示例
/*$status = checkTimeStatus($start_times, $end_times);
$is_expired = $status['is_expired'];*/
#判断时间格式是否标准
function isStandardTime($timeStr) {
    return (bool) DateTime::createFromFormat('Y-m-d H:i:s', $timeStr);
}

#处理状态
function status_desc($key)
{
    $deal_arr=[
        '1'=>'待处理',
        '2'=>'处理中',
        '3'=>'已处理-违规',
        '4'=>'已处理-不违规',
        '5'=>'已忽略'

    ];
    if(isset($deal_arr[$key])){
        return $deal_arr[$key];
    }else{
        return $key;
    }
}
#只包含中文字符

function isPureChinese($string) {
    return preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $string) === 1;
}

# json参数一直是空字符串
function getJsonValue($request, $key, $default = '') {
    return $request->json($key) ?? $default;
}


# input参数一直是空字符串
function getInputValue($request, $key, $default = '') {
    return $request->input($key) ?? $default;
}

#20到30 的随机数
function getRandomInRange($min=20,$max=30) {
    // 确保参数是有效的整数
    $min = (int)$min;
    $max = (int)$max;
    
    // 如果最小值大于最大值，交换它们
    if ($min > $max) {
        list($min, $max) = [$max, $min];
    }
    
    // 如果最小值等于最大值，直接返回该值
    if ($min === $max) {
        return $min;
    }
    
    return mt_rand($min, $max);
}

function platform_transform(){
    
}

/**
 * 二维数组按发布时间排序
 * @param array $data 二维数组
 * @param string $field 时间字段名
 * @param string $order 排序方式：asc-升序 desc-降序
 * @return array 排序后的数组
 */
function sortByPublishTime($data, $field = 'publish_time', $order = 'desc') {
    if (empty($data) || !is_array($data)) {
        return $data;
    }
    
    // 检查第一个元素是否有需要的字段
    $firstElement = reset($data);
    if (!is_array($firstElement) || !array_key_exists($field, $firstElement)) {
        return $data;
    }
    
    usort($data, function($a, $b) use ($field, $order) {
        $timeA = strtotime($a[$field] ?? '');
        $timeB = strtotime($b[$field] ?? '');
        
        $timeA = $timeA ?: 0;
        $timeB = $timeB ?: 0;
        
        if ($order === 'asc') {
            return $timeA <=> $timeB;
        } else {
            return $timeB <=> $timeA;
        }
    });
    
    return $data;
}
